package com.rzj.book.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.rzj.book.en.Emp;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName BaseController
 * @Description TODO
 * @Author Administrator
 * @Date 2020/5/14 22:51
 * @Version 1.0
 */
public class BaseController {
    /**
     * 获取request对象
     */
    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获取Response对象
     */
    public HttpServletResponse getResponse() {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        return response;
    }

    /**
     * 获取Session对象
     */
    public HttpSession getSession() {
        return getRequest().getSession();

    }

    public void write(String jsonString){
        try {
            //响应对象
            HttpServletResponse response = getResponse();
            //设置编码
            response.setContentType("text/html;charset=utf-8");
            //输出给页面
            response.getWriter().write(jsonString);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendJSONArrayGrid(JSONArray jsonArray){
        //返回前端的JSON数据
        Map<String, Object> rtn = new HashMap<String, Object>();
        rtn.put("rows",jsonArray);
        rtn.put("total",jsonArray.size());
        //JSON.toJSONString(rtn) => {"success":true,"message":'超级管理员'}
        write(JSON.toJSONString(rtn));
    }

    public void sendJSONArrayCountGrid(JSONArray jsonArray,Integer total){
        //返回前端的JSON数据
        Map<String, Object> rtn = new HashMap<String, Object>();
        rtn.put("rows",jsonArray);
        rtn.put("total",total);
        //JSON.toJSONString(rtn) => {"success":true,"message":'超级管理员'}
        write(JSON.toJSONString(rtn));
    }

    public void ajaxReturn(boolean success, String message){
        //返回前端的JSON数据
        Map<String, Object> rtn = new HashMap<String, Object>();
        rtn.put("success",success);
        rtn.put("message",message);
        //JSON.toJSONString(rtn) => {"success":true,"message":'超级管理员'}
        write(JSON.toJSONString(rtn));
    }

    public Emp getLoginUser() {
        return (Emp) getSession().getAttribute("loginUser");
    }

}
